package com.zlz.server.config.security;

import com.zlz.server.constant.RoleConstant;
import com.zlz.server.pojo.Menu;
import com.zlz.server.pojo.Role;
import com.zlz.server.service.IMenuService;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * @author: zlz
 * @date: 2021/1/20 22:41
 * @description: 权限控制，根据url请求所需的角色
 * @since: JDK1.8
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {
    @Resource
    private IMenuService iMenuService;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) {
        // 获取请求的url
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        List<Menu> menus = iMenuService.getMenusByRole();
        for (Menu menu : menus) {
            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                return SecurityConfig.createList(str);
            }
        }
        // 没匹配上赋予登录的角色
        return SecurityConfig.createList(RoleConstant.ROLE_LOGIN);
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
